package cn.kk.config;

import cn.hutool.core.util.RandomUtil;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import lombok.Data;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * SwaggerConfig
 * @author kinoko
 */
@Data
public class BaseSwaggerConfig {

    // 是否开启swagger
    private Boolean enable;
    // 文档标题
    private String title;
    // 文档描述
    private String description;
    // 版本号
    private String version;
    // 许可证
    private String license;
    // 许可证URL
    private String licenseUrl;
    // 服务条款URL
    private String termsOfServiceUrl;
    // ip
    private String host;
    // 基础路径
    private String basePath;
    // 基包扫描路径
    private String basePackage;
    // 维护人信息
    private ContactInfo contact;

    @Data
    public static class ContactInfo {
        private String name;
        private String email;
        private String url;
    }

    /**
     * 根据@Tag 上的排序，写入x-order
     *
     * @return the global open api customizer
     */
    @Bean
    public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
        return openApi -> {
            if (openApi.getTags()!=null){
                openApi.getTags().forEach(tag -> {
                    Map<String,Object> map=new HashMap<>();
                    map.put("x-order", RandomUtil.randomInt(0,100));
                    tag.setExtensions(map);
                });
            }
            if(openApi.getPaths()!=null){
                openApi.addExtension("x-test123","333");
                openApi.getPaths().addExtension("x-abb",RandomUtil.randomInt(1,100));
            }

        };
    }

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title(title)
                        .version(version)
                        .description(description)
                        .termsOfService(termsOfServiceUrl)
                        .license(new License().name(license)
                                .url(licenseUrl)));
    }

}


